package kr.pe.osdev.dao.jdbc.mysql;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import kr.pe.osdev.dao.CategoryDao;
import kr.pe.osdev.dao.jdbc.BaseJdbcDao;
import kr.pe.osdev.domain.Category;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class CategoryDaoImpl extends BaseJdbcDao implements CategoryDao {

	@Override
	public List<Category> findListByUserSid(Category category) throws DataAccessException {
		return null;
	}   
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Category> findRootListByUserSid(Category category) throws DataAccessException {
        String sql = getMessageSourceAccessor().getMessage("category.findRootListByUserSid");
        
        Object[] obj = new Object[] { category.getUserSid(),
        		category.getCategoryType(),
        		category.getUseYn()};
        
        return (List<Category>) getJdbcTemplate().query(sql, obj, getRowMapper(true));
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Category> findChildListByUserSid(Category category) throws DataAccessException {
		String sql = getMessageSourceAccessor().getMessage("category.findChildListByUserSid");
		
		Object[] obj = new Object[] { category.getCategoryHieararchy(),
				category.getUserSid(),
				category.getCategoryType(),
				category.getUseYn()};
		
		return (List<Category>) getJdbcTemplate().query(sql, obj, getRowMapper(true));
	}
	
    private RowMapper getRowMapper(final boolean mode) {
        RowMapper rowMapper = new RowMapper() {
            public Object mapRow(ResultSet rs, int rownum) throws SQLException {
                return makeData(rs, mode);
            }
        };
        
        return rowMapper;
    }
    
    private Category makeData(ResultSet rs, boolean mode) throws SQLException {
    	Category category = new Category();
        category.setSid(rs.getString("SID"));
        category.setCategoryHieararchy(rs.getString("CATEGORY_HIEARARCHY"));
        category.setCategoryName(rs.getString("CATEGORY_NAME"));
        category.setCategoryType(rs.getString("CATEGORY_TYPE"));
        category.setUserSid(rs.getString("USER_SID"));
        category.setModifyDate(rs.getString("MODIFY_DATE"));
        category.setModifyTime(rs.getString("MODIFY_TIME"));
        category.setRegistDate(rs.getString("REGIST_DATE"));
        category.setRegistTime(rs.getString("REGIST_TIME"));
        category.setUseYn(rs.getString("USE_YN"));
        
        if(mode) {
            category.setIsLeaf(rs.getString("IS_LEAF"));
        }
        
        return category;
    }
}